package com.ruoyi.system.fastgpt.service.impl;

import com.google.common.collect.Lists;
import com.ruoyi.system.fastgpt.service.FastGptService;
import com.ruoyi.system.fastgpt.vo.FastGptRequest;
import com.ruoyi.system.fastgpt.vo.FastGptResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class FastGptServiceImpl implements FastGptService {
	@Autowired
	private RestTemplate restTemplate;

	@Value("${fastgpt.api.key}")
	private String apiKey;
	@Value("${fastgpt.api.base-url}")
	private String baseUrl;

	@Override
	public FastGptResponse sendMessage(String content, Map<String, Object> variables) {
		FastGptRequest.ChatMessage chatMessage = new FastGptRequest.ChatMessage();
		chatMessage.setRole("user");
		chatMessage.setContent(content);

		List<FastGptRequest.ChatMessage> messageList = Lists.newArrayList();
		messageList.add(chatMessage);

		FastGptRequest request = new FastGptRequest();
		request.setModel("fastgpt-default");
		request.setStream(false);
		request.setTemperature(0.7);
		request.setMessages(messageList);
		request.setVariables(variables);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("Authorization", "Bearer " + apiKey);

		HttpEntity<FastGptRequest> entity = new HttpEntity<>(request, headers);

		try {
			ResponseEntity<FastGptResponse> response = restTemplate.exchange(
					baseUrl,
					HttpMethod.POST,
					entity,
					FastGptResponse.class);

			return response.getBody();
		} catch (HttpClientErrorException e) {
			throw new RuntimeException("FastGPT API调用失败: " + e.getResponseBodyAsString(), e);
		} catch (RestClientException e) {
			throw new RuntimeException("调用FastGPT服务出错", e);
		}
    }
}
